#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" By Martin Senande-Rivera
    For Towards and atmosphere more favourable to firestorm development in Europe """

import os
import glob, sys
import numpy as np
import xarray as xr
import pandas as pd

GCM=sys.argv[1]  # Enter GCM
RCM=sys.argv[2]  # Enter RCM
rcp=sys.argv[3]  # Enter RCP scenario

path_fwi='../0-DATA/FWI/'+RCM+'/'+GCM+'/FWI/'
path_outs='./'+RCM+'/'+GCM+'/'

# Read files
fwis=sorted(glob.glob(path_fwi+'fwi_historical_*.nc')+glob.glob(path_fwi+'fwi_'+rcp+'_*.nc'))
FWI = xr.open_mfdataset(fwis,combine='by_coords')['fwi']

FWI = FWI.sel(time=slice('1981-01-01','2020-12-31'))

FWI_90 = FWI.resample(time='1Y',skipna=True).quantile(0.90, dim='time') # FWI daily 90th percentile
FWI_mean = FWI_90.mean(dim='time',skipna=True)                          # FWI 90th percentile time average
FWI_thres = 11.2                                                        # FWI minimum threshold
FWI_mean = xr.where(FWI_mean<FWI_thres,FWI_thres,FWI_mean)              # Where FWI 90th percentile is below FWI minimum threshold, 11.2 is the threshold
FWI_mean.to_netcdf(path_outs+'FWI_90threshold_'+rcp+'.nc')              # Save output
